package com.collection.dao;


import java.util.List;

import org.springframework.stereotype.Repository;

import com.collection.common.base.BaseDaoImpl;
import com.collection.entity.BaseStrategy;
import com.collection.entity.CollectionTask;
import com.collection.entity.ContentStrategy;

@Repository
public class ContentStrategyDao extends BaseDaoImpl<ContentStrategy> {
	
	public void createCollectionTable(ContentStrategy contentStrategy) {
		deleteCollectionTable(contentStrategy);
		if(contentStrategy != null) {
			CollectionTask task = contentStrategy.getCollectionTask();
			if(task != null) {
				
				String collectionTableName = task.getTaskAlias();
				
				StringBuffer sb = new StringBuffer("create table ");
				sb.append(collectionTableName+"(id int AUTO_INCREMENT, hasCollection tinyint default '0', hasPublish tinyint default '0',pageUrl varchar(1000),");
				if(contentStrategy != null) {
					List<BaseStrategy> baseStrategies = contentStrategy.getBaseStrategies();
					if(baseStrategies != null && baseStrategies.size() > 0) {
						for(BaseStrategy bs : baseStrategies) {
							sb.append(bs.getFieldName()+" mediumtext,");
						}
					}
				}
				sb.append("primary key (id))");
				jdbcTemplate.execute(sb.toString());
				
				/*
				 * 建索引
				 */
				jdbcTemplate.execute("CREATE INDEX "+collectionTableName+"_pageUrl_index ON "+collectionTableName+"(pageUrl)");
				
				jdbcTemplate.execute("CREATE INDEX "+collectionTableName+"_hasCollection_index ON "+collectionTableName+"(hasCollection)");
				
				jdbcTemplate.execute("CREATE INDEX "+collectionTableName+"_hasPublish_index ON "+collectionTableName+"(hasPublish)");
			}
		}
	}
	
	public void deleteCollectionTable(ContentStrategy contentStrategy) {
		if(contentStrategy != null) {
			CollectionTask task = contentStrategy.getCollectionTask();
			if(task != null) {
				
				String collectionTableName = task.getTaskAlias();
				
				jdbcTemplate.execute("DROP TABLE IF EXISTS "+collectionTableName);
			}
		}
	}
}
